# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time   :  2019/7/4 10:50
@Author :  geqh
@file   :  api.py
"""
from flask import Flask, request
from tagCN import tag_CN
from tagEN import tag_EN
from utils.result import *
from utils.log import *
import json

app = Flask(__name__)
dict_map_cn = tag_CN.load_dict()
dict_map_en = tag_EN.load_dict()


# 接口classification
@app.route('/tag', methods=['GET', 'POST'])
def tag():
    # noinspection PyBroadException
    try:  # 必要参数
        text = request.values['text']
        lang = request.values['lang']
    except:
        errMsg = 'parameter [text/lang] is lost'
        res_fail = result(False, errMsg, None)
        res = json.dumps(obj=res_fail.__dict__, ensure_ascii=False)
        logger.error(errMsg)
        return res

    logger.info("parameter text--" + text)
    logger.info("parameter lang--" + lang)

    # 英文
    if lang == 'en':
        res = tag_EN.tagEN(text, dict_map_en)
        res_suc = result(True, None, res)
        res = json.dumps(obj=res_suc.__dict__, ensure_ascii=False)
        return res
    # 中文
    elif lang == 'cn':
        res = tag_CN.tagCN(text, dict_map_cn)
        res_suc = result(True, None, res)
        res = json.dumps(obj=res_suc.__dict__, ensure_ascii=False)
        return res
    else:
        res_fail = result(False, 'invalid language', None)
        res = json.dumps(obj=res_fail.__dict__, ensure_ascii=False)
        return res


# 可直接测试
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8018)
